import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:C20Driver/config/service_api.dart';
import 'package:C20Driver/utils/toast.dart';
import 'package:package_info/package_info.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:C20Driver/model/get_version_message.dart';
import 'package:C20Driver/service/service_method.dart';
import 'package:C20Driver/widget/update_version.dart';

/// App版本升级类
class AppUpdate {
  /// 01 => android   02 => ios
  String appCode = '01';
  var _serviceVersionCode, _serviceVersionApp, _serviceAppStoreUrl;
  List _introductionUpgrade;

  String isSet = '00';
  AppUpdate({this.isSet});

  /// 检测app更新
  Future<void> getAppUpdate(context) {
    //每次打开APP获取当前时间戳
    var timeEnd = DateTime.now().millisecondsSinceEpoch;
    //获取"Later"保存的时间戳
    return _incrementCounter(timeEnd, context);
  }

  Future<void> _incrementCounter(timeEnd, context) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var getIns = prefs.getInt("timeStart");
    if (getIns == null) {
      //第一次打开APP时执行"版本更新"的网络请求
      _getNewVersionAPP(context);
    } else if (getIns != 0 && timeEnd - getIns >= 24 * 60 * 60 * 1000) {
      //如果新旧时间戳的差大于或等于一天，执行网络请求
      _getNewVersionAPP(context);
    }
  }

  // 执行版本更新的网络请求
  Future<void> _getNewVersionAPP(context) async {
    if (Platform.isIOS) {
      //ios相关代码
      appCode = '02';
    } else if (Platform.isAndroid) {
      //android相关代码
      appCode = '01';
    }
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String _currentVersionCode = packageInfo.version;
    DioUtils().requestAppUpdata(formData: {
      'appCode': appCode,
      'versionId': ServiceApi.appId,
      'versionCode': _currentVersionCode
    }).then((res) {
      if (res.length != 0) {
        var getVersionMessageData = GetVersionMessage.fromJson(res);
        _serviceVersionCode = getVersionMessageData.versionCode; //版本号
        _serviceAppStoreUrl = getVersionMessageData.downloadUrl;
        _serviceVersionApp = getVersionMessageData.downloadUrl; // 下载的URL
        if (getVersionMessageData.optimtion.length == 0) {
          _introductionUpgrade = getVersionMessageData.repair; // 升级简介
        } else {
          _introductionUpgrade = getVersionMessageData.optimtion; // 升级简介
        }

        return _showNewVersionAppDialog(context); //弹出对话框
      } else {
        if (isSet == '01') {
          ToastX.center('您的APP已是最新版本');
          isSet = '00';
        }
      }
      return '';
    });
  }

  // 更新 app 弹窗
  Future<void> _showNewVersionAppDialog(context) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false, // user must tap button!
      builder: (BuildContext context) {
        final data = UpdateVersion(
          appStoreUrl: _serviceAppStoreUrl,
          versionName: 'v$_serviceVersionCode',
          apkUrl: _serviceVersionApp,
          contentTxt: _introductionUpgrade,
        );
        return UpdateVersionDialog(data: data);
      },
    );
  }
}
